#include "addform.h"
#include "ui_addform.h"
#include <QSqlQuery>
#include <QMessageBox>
#include <QString>
#include <QDebug>

AddForm::AddForm(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::AddForm)
{
    ui->setupUi(this);
    // cancel
    QObject::connect(ui->cancelButton,&QPushButton::clicked,[&]{
        this->parentWidget()->show();
        this->deleteLater();
    });
}

AddForm::~AddForm()
{
    delete ui;
}

void AddForm::on_saveButton_clicked()
{
    // add
    QSqlQuery q;
    q.prepare("INSERT INTO projects (projectName, priority, status, businessLeader, softWareLeader, startTime, consumeTime, endTime, requirementsDocumentation, bom, softwareRecords) "
              "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    q.addBindValue(ui->lineEditProjectName->text());
    q.addBindValue(ui->lineEditPriority->text());
    q.addBindValue(ui->lineEditStatus->text());
    q.addBindValue(ui->lineEditBusinessLeader->text());
    q.addBindValue(ui->lineEditSoftWareLeader->text());
    q.addBindValue(ui->dateTimeEditStartTime->text());
    q.addBindValue(ui->spinBox->value());
    q.addBindValue(ui->dateTimeEditEndTime->text());
    q.addBindValue(ui->lineEditRequirementsDocumentation->text());
    q.addBindValue(ui->lineEditBom->text());
    q.addBindValue(ui->lineEditSoftwareRecords->text());

    if (q.exec()) {
        QMessageBox::information(this, "成功", "添加成功");
    } else {
        QMessageBox::warning(this, "错误", "添加失败");
    }
    this->parentWidget()->show();
    this->deleteLater();
}

void AddForm::on_dateTimeEditStartTime_dateChanged(const QDate &date)
{
    QDate startDate = ui->dateTimeEditStartTime->date();
    QDate endDate = ui->dateTimeEditEndTime->date();

    int daysDifference = startDate.daysTo(endDate);  // 同样注意顺序
    ui->spinBox->setValue(daysDifference);
    qDebug() << daysDifference;
}


void AddForm::on_dateTimeEditEndTime_dateChanged(const QDate &date)
{
    QDate startDate = ui->dateTimeEditStartTime->date();
    QDate endDate = ui->dateTimeEditEndTime->date();

    int daysDifference = startDate.daysTo(endDate);  // 同样注意顺序
    ui->spinBox->setValue(daysDifference);
    qDebug() << daysDifference;
}


void AddForm::on_spinBox_valueChanged(int arg1)
{
    QDateTime startDateTime = ui->dateTimeEditStartTime->dateTime();

    // 只取日期部分进行加减
    QDate startDate = startDateTime.date();
    QDate endDate = startDate.addDays(arg1);  // 加上工作日天数

    // 设置到结束时间控件中（可选）
    ui->dateTimeEditEndTime->setDate(endDate);
}

